import requests
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from django.views import View

from my_django import MyRedis
from my_django.ser import UserSer

from .models import *

import redis

from rest_framework.views import APIView
from rest_framework.response import Response


# 注册
class RegisteredView(APIView):
    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")
        user_li = User.objects.filter(username=username)
        if user_li:
            return Response({"msg": "该用户已存在", 'code': 400})
        User.objects.create(username=username, password=password)
        return Response({"msg": "注册成功", 'code': 200})


# 登录
class LoginView(APIView):
    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")

        r = redis.Redis()
        # 判断用户是否存在黑名单
        if r.get(str(username) + "black"):
            return Response({"msg": "您的账号被锁定,等待30分钟", 'code': 400})
        # 反之,进行登录
        user_li = User.objects.filter(username=username, password=password)
        # 判断密码是否正确
        if user_li:
            return Response({"msg": "登陆成功", 'code': 200, 'uid': user_li[0].id})

        # 判断是否存在该键值对,如果不存在,则进行创建
        if r.get(str(username)) == None:
            r.set(str(username), 0)

        # 如果是第一次密码错误,开始计时
        if int(r.get(str(username))) == 0:
            r.expire(str(username), 200)
            # 进行累加
            r.incrby(str(username), 1)
            return Response({"msg": "用户名或密码错误", 'code': 400})

        else:
            # 在五分钟错误五次 进行封禁
            if int(r.get(str(username))) == 5:
                r.set(str(username) + "black", str(password))
                # 封禁时间
                r.expire(str(username) + "black", 1800)
                return Response({"msg": "您的账号被锁定30分钟", 'code': 400})
            # 进行累加
            r.incrby(str(username), 1)
            return Response({"msg": "用户名或密码错误", 'code': 400, 'count': r.get(str(username))})


class UserView(APIView):
    def get(self, request):
        user_li = User.objects.all().values()
        return Response(user_li)

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')
        print(username, password, email, phone)

        User.objects.create(username=username, password=password, phone=phone, email=email)
        return Response({'msg': '添加成功'})

    def delete(self, request):
        uid = request.GET.get('uid')
        User.objects.filter(id=uid).delete()
        return Response({'msg': '删除成功'})

    def put(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')
        User.objects.filter(username=username).update(password=password, phone=phone, email=email)
        return Response({'code': 200})


class ShowUserView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        user_li = User.objects.filter(pk=id).values().first()
        return Response(user_li)


from UserApp import tasks


def ctest(request, *args, **kwargs):
    res = tasks.print_test.delay()
    # 任务逻辑
    return JsonResponse({'status': 'successful', 'task_id': res.task_id})


import urllib
from UserApp.tesk_queue import MyQueue

myq = MyQueue()


class GetJob(APIView):
    def get(self, request):
        r = redis.Redis()

        # 出队
        myjob = myq.pop()
        a = User.objects.filter(username=myjob[1]).first()
        key = 'que'
        if a:
            r.hset(key, myjob[0], '用户名错误')
            return Response({'msg': '用户名重复', 'code': '201'})
        User.objects.filter(pk=int(myjob[0])).update(username=myjob[1])
        r.hset(key, myjob[0], '修改用户名成功')
        return Response({'msg': '修改用户名成功', 'code': '200'})


from UserApp import tasks


class Celery_username(APIView):
    def post(self, request):
        username = request.data.get('username')
        new_username = request.data.get('new_username')
        gai = tasks.update_username(username, new_username)
        return JsonResponse(gai, safe=False)


# 修改用户名(微信号)
class UpdateUserName(APIView):

    def get(self, request):
        # 用户名
        username = request.GET.get('username', None)
        new_username = request.GET.get('username', None)

        a = User.objects.filter(username=username).first()
        uid = a.id
        # 入队
        myq.push((uid, new_username))
        return Response({'msg': '正在审核中，请耐心等待'})


class QueueRedis(APIView):

    def get(self, request):
        # 获取任务
        id = request.GET.get("id")
        username = request.GET.get("username")
        # # 旧密码
        # password1 = request.GET.get("password1")
        # # 新密码
        # password2 = request.GET.get("password2")

        user_li = User.objects.filter(id=id).first()

        r = redis.Redis()

        # 判断是否含有重复的
        my_list = myq.get()
        for i in my_list:
            if int(i[0]) == int(id):
                print(myq.get(), '--------*******-----------')
                r.set("list" + str(username), "该用户已存在该列表")
                return Response({"msg": "该用户名已存在列表中", 'code': 400})

        # 判断是否是VIP
        if user_li.select != 0:
            # 如果是VIP则添加到前面
            myq.insert(0, (id, username))
            r.set("list" + str(username), "该VIP用户已存在该列表")
            return Response({"msg": "VIP用户", 'code': 200})

        # 入队操作
        myq.push((id, username))

        # 查看数据
        print(myq.get(), '--------*******-----------')
        r.set("list" + str(username), "该用户正在审核中,请耐心等待")
        return Response({"msg": "正在审核中,请耐心等待", 'code': 200})

        # # 首先连接Redis
        # r = redis.Redis()

        # user_li = AntUser.objects.filter(id=id).first()
        # if password1 == user_li.password and password1 != password2:
        #     AntUser.objects.filter(id=id).update(username=username, password=password2)
        #     return Response({"msg": "修改成功", 'code': 200})
        # return Response({"msg": "失败", 'code': 400})

    # from user.text_queue import MyQueue
    # import datetime
    # class UpdateUser(APIView):
    #     def post(self, request):
    #         # 获取id
    #         uid = request.data.get('uid', None)
    #         # 用户名
    #         username = request.data.get('username', None)
    #         level = User.objects.get(id=uid).level
    #         # 入队
    #         myq = MyQueue()
    #         myq.push(uid=uid, level=level, username=username)
    #
    #         myq.printf()
    #         return Response({'msg': '审核中请等待'})
    #
    #     def get(self, request):
    #         myq = MyQueue()
    #         return Response({'data': myq.show()})
    #
    #     def put(self, request):
    #         myq = MyQueue()
    #         start = time.time()
    #         rs = myq.pop()
    #         end = time.time()
    #         print("用了", end - start, '秒')
    #         return Response({'data': rs, 'time': end - start})


class Mymiddle(APIView):
    qx = 1

    def get(self, request):
        # 返回结果中间件中结果
        return Response({'data': qx == request.level})

    def put(self, request):
        global qx
        qx = int(not qx)
        print(qx)
        return Response({'msg': '已修改'})


# 位运算，权限管理
class WeiAPI(APIView):

    def post(self, request):
        pass


# 三方登录
class Gitee(View):

    def get(self,request):
        return redirect("https://gitee.com/oauth/authorize?client_id=d3c76aaa200c479636bc44245e2dd5c752a4b4ce0e832e77651e7bf88080d572&redirect_uri=http://localhost:8000/gitee_back&response_type=code")

class GiteeBack(View):

    def get(self,request):

        code = request.GET.get("code",None)

        r = requests.post("https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=d3c76aaa200c479636bc44245e2dd5c752a4b4ce0e832e77651e7bf88080d572&redirect_uri=http://localhost:8000/gitee_back&client_secret=9af873978dee3d6c59716c82f0056eab5722cb36afe8c2508f460d63b6e391e6" % code)
        print(r.text)

        return HttpResponse("ok")
# r = requests.get("https://gitee.com/oauth/authorize?client_id=d3c76aaa200c479636bc44245e2dd5c752a4b4ce0e832e77651e7bf88080d572&redirect_uri=http://localhost:8000/gitee_back&response_type=code")
#
# print(r.text)
def ding_url(request):
    appid = 'dingoarj2uw11acmdnpzuk'  # 替换成自己的appid
    redirect_uri = 'http://localhost:8000/ding_back/'  # 替换成自己的回调路由

    return redirect(
        'https://oapi.dingtalk.com/connect/qrconnect?appid=' + appid + '&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' + redirect_uri)


import time
import hmac
import base64
from hashlib import sha256
import urllib
import json


# 构造钉钉回调方法
def ding_back(request):
    # 获取code
    code = request.GET.get("code")

    t = time.time()
    # 时间戳
    timestamp = str((int(round(t * 1000))))
    # 替换成自己的appSecret
    appSecret = '3imz5jFwM3ZWme84u-2eWrM-FV47rRiTQf2WYrzkOqJ6mrlMDCCek2Lr2zQ8ysrR'
    # 构造签名
    signature = base64.b64encode(
        hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())
    # 请求接口，换取钉钉用户名
    payload = {'tmp_auth_code': code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
        signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoarj2uw11acmdnpzuk",
                        data=json.dumps(payload), headers=headers)  # accessKey替换成自己的appid

    res_dict = json.loads(res.text)
    print(res_dict)
    return HttpResponse(res.text)


# 钉钉登录
class Ding_Login(APIView):

    def post(self, request):
        username = request.data.get('username')
        DingTalkUser.objects.get(username=username)
        return Response({"msg": '登陆成功', 'code': 200})
# 权限修改
class Quanxian(APIView):

    def put(self, request):
        level = request.data.get('level')
        username = request.data.get('username')
        print(level,id,'11111111111111111111111111111111111')
        User.objects.filter(username=username).update(level=level)
        return Response({'code': 200})

    def get(self, request):
        user_li = User.objects.all()
        ser = UserSer(user_li,many=True)
        return Response(ser)

